package com.bifrost.repository;

import com.bifrost.entity.OrderReturn;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.keyvalue.repository.config.QueryCreatorType;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author rangf
 * @date 2018/3/7
 */
public interface OrderReturnRepository extends JpaRepository<OrderReturn, Long>, JpaSpecificationExecutor<OrderReturn> {

    @Query(value = "SELECT * FROM `ORDER_RETURN` O WHERE O.ID=?1 AND O.CUSTOMER_ID=?2", nativeQuery = true)
    OrderReturn getByIdAndCustomerId(Long returnId, Long customerId);

    /**
     *
     * @param returnId 售后id
     * @param status 状态
     * @return
     */
    @Modifying
    @Transactional
    @Query(value = "UPDATE ORDER_RETURN O SET O.STATUS=?2 WHERE O.ID=?1", nativeQuery = true)
    int updateStatus(Long returnId, String status);

    /**
     * 查询所有有效的售后
     *
     * @param orderId
     * @return
     */
    @Query(value = "SELECT * FROM ORDER_RETURN O WHERE O.RELATED_ORDER_ID=?1 AND O.STATUS <> 'CANCELED' ", nativeQuery = true)
    List<OrderReturn> findVaildRefundOrders(Long orderId);

    /**
     * 未处理完售后单数量
     *
     * @param customerId
     * @param storeId
     * @return
     */
    @Query(value = "SELECT COUNT(*) FROM `ORDER_RETURN` O WHERE O.CUSTOMER_ID=?1 " +
            "AND O.MERCHANT_STORE_ID=?2 AND O.`STATUS` NOT IN('CANCELED','FINISHED')", nativeQuery = true)
    long countNotHandledReturns(Long customerId, Long storeId);

    /**
     * 注意！！！该方法返回的实体只包含id、refundTotal属性
     * @param Id
     * @return
     */
    @Query("select new OrderReturn(o.id,o.refundTotal)from OrderReturn o where o.id = ?1")
    OrderReturn findByOrderReturnId(Long Id);


    /**
     * 获取指定退单号的退单
     * @param returnNumber
     * @return
     */
    OrderReturn findByReturnNumber(String returnNumber);

    OrderReturn findFirstByReturnNumber(String transNo);
}
